﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace JJYYCore.CSV
{
    public class CSVManager
    {
        private ResourcesLoaderBase resourcesLoader;

        public List<T> LoadCSVData<T>(string dataName,int titleCount = 0) where T:GameDataBase,new()
        {
            var csvFile = resourcesLoader.Load<TextAsset>(dataName);
            if(csvFile == null)
            {
                Debug.LogError("不存在指定名称的CSV文件,文件名为:"+dataName);
                return null;
            }

            return HandleLoadedAssets<T>(csvFile, titleCount);
        }

        public void LoadCSVDataCallback<T>(string dataName,UnityAction<List<T>> callback, int titleCount = 0) where T:GameDataBase,new()
        {
            resourcesLoader.LoadCallBack(dataName, (TextAsset asset) => {
                var resultList = HandleLoadedAssets<T>(asset, titleCount);
                callback(resultList);
            });
        }

        private List<T> HandleLoadedAssets<T>(TextAsset csvFile,int titleCount) where T : GameDataBase, new()
        {
            var lines = csvFile.text.Split('\n');
            var rows = new List<string[]>();

            for (int i = titleCount; i < lines.Length - 1; i++)
            {
                var selectLine = lines[i];
                var selectRow = selectLine.Split(',');

                rows.Add(selectRow);
            }

            var datas = GameDataBase.GetDatasByCSVList<T>(rows);
            return datas;
        }

        public CSVManager(ResourcesLoaderBase loaderBase)
        {
            resourcesLoader = loaderBase;
        }
    }
}
